package com.example.app.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.example.app.R

@Composable
fun NetworkImageLoader(url: String) {
    val painter = rememberAsyncImagePainter(
        model = ImageRequest.Builder(LocalContext.current)
            .data(url)
//            .placeholder(R.drawable.ic_launcher_background) // 占位符图片
            .error(R.drawable.ic_launcher_foreground) // 错误图片
            .build()
    )

    Box(modifier = Modifier
        .fillMaxWidth()
        .aspectRatio(16 / 9f)) {
        Image(
            painter = painter,
            contentDescription = null,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop
        )

        // 显示加载中的进度条
        if (painter.state is AsyncImagePainter.State.Loading) {
            LinearProgressIndicator(
                modifier = Modifier.align(Alignment.Center)
            )
        }

        // 显示加载失败的提示
        if (painter.state is AsyncImagePainter.State.Error) {
            Text(
                text = "加载失败",
                modifier = Modifier.align(Alignment.Center)
            )
        }
    }
}